package com.practice.bootdemo.config;

import com.practice.bootdemo.annotation.ParamValidate;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :admin
 * @description: form表单参数校验
 * @create date: 2019/12/18 22:24
 */
@Aspect
@Configuration
public class ParamValidatedConfig {
    @Pointcut("@annotation(com.practice.bootdemo.annotation.ParamValidate)")
    public void validatedPointCut() {}

    ;

    @Before("validatedPointCut()")
    public void printLog(final JoinPoint joinPoint)  {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        new ArrayList<>();

        List parameterNames = CollectionUtils.arrayToList(signature.getParameterNames());
        List parameterValue = CollectionUtils.arrayToList(joinPoint.getArgs());
        ParamValidate annotation = signature.getMethod().getAnnotation(ParamValidate.class);
        List validatedParamList = CollectionUtils.arrayToList(annotation.validatedParamArr());
        if (validatedParamList.size()==0){
            if (parameterValue.size()!=0){
                for (Object o : parameterValue) {
                    if (ObjectUtils.isEmpty(o)){
                        throw new RuntimeException(annotation.validatedMsg());
                    }
                }
            }
        }else {
            for (Object o : validatedParamList) {
                int index = parameterNames.indexOf(o);
                if (index<0){
                    throw new RuntimeException(annotation.errConfigMsg());
                }else {
                    Object validatedValue = parameterValue.get(index);
                    if (ObjectUtils.isEmpty(validatedValue)){
                        throw new RuntimeException(annotation.validatedMsg());
                    }
                }

            }
        }
    }

}
